import json

from flask import Flask, request, render_template
import Winner
from alpha_beta import searcher
import numpy as np

app = Flask(__name__)


@app.route('/api/gobang', methods=['GET', 'POST'])
def gobang():
    if request.method == 'POST':
        a = request.get_data()
        data = json.loads(a)  # 获取json数据
        data["matrix"] = np.asarray(data["matrix"])  # 转换数组
        ai = searcher(data["matrix"])  # 初始化
        ai.board = data["matrix"]  # 设置棋盘数据
        score, x, y = ai.search(data["value"], data["depth"])  # ai搜索下棋位置，传棋子类型和深度
        if data["matrix"][x][y] == 2 or data["matrix"][x][y] == 1:
            pass  # ai已有棋子，跳过
        else:
            data["matrix"][x][y] = data["value"]  # 落子
            text = "白棋" if data["value"] == 1 else "黑棋"
            data["label"] = text + "落子:(" + str(y) + "," + str(x) + ")"  # 落子消息
            data["value"] = 1 if data["value"] == 2 else 2  # 切换可落子对象
            data["win"] = Winner.winner(data["matrix"])  # 判断谁赢
        data["matrix"] = data["matrix"].tolist()  # 转换数组list
        return json.dumps(data)  # 响应数据给前端
    else:
        return '<h1>只接受post请求！</h1>'


@app.route('/api/winner', methods=['GET', 'POST'])
def winner():
    if request.method == 'POST':
        a = request.get_data()
        data = json.loads(a)  # 获取json数据
        data["matrix"] = np.asarray(data["matrix"])  # 转换数组
        data["win"] = Winner.winner(data["matrix"])  # 判断谁赢
        data["matrix"] = data["matrix"].tolist()  # 转换数组list
        return json.dumps(data)  # 响应数据给前端
    else:
        return '<h1>只接受post请求！</h1>'


@app.route('/')
def index():
    return render_template('index.html')


if __name__ == '__main__':
    app.debug = True
    app.run()
